package dept_service

import (
	"encoding/json"
	"models"
	"pkg/gredis"
	"pkg/logging"
	"service/cache_service"
)

type Dept struct {
	ID   int
	PID  int
	name string
}

func (d *Dept) getMaps() map[string]interface{} {
	maps := make(map[string]interface{})
	maps["deleted_on"] = 0
	return maps
}

// 部门列表
func (d *Dept) GetAll() ([]*models.Dept, error) {
	var (
		depts, cacheDepts []*models.Dept
	)

	// 查缓存
	cache := cache_service.Dept{}
	key := cache.GetDeptsKey()
	if gredis.Exists(key) {
		data, err := gredis.Get(key)
		if err != nil {
			logging.Error(err)
		} else {
			json.Unmarshal(data, &cacheDepts)
			return cacheDepts, nil
		}
	}

	// 查库
	depts, err := models.GetDepts(d.getMaps())
	if err != nil {
		return nil, err
	}

	// 存缓存
	gredis.Set(key, depts, 3600)
	return depts, nil
}

// 部门树形
func (d *Dept) GetTree(i int) (trees []*models.DeptTree, err error) {
	depts, err := models.GetDepts(d.getMaps())
	if err != nil {
		return nil, err
	}
	return newTree(depts, 0), nil
}

// 创建部门树
func newTree(depts []*models.Dept, pid int) (trees []*models.DeptTree) {
	for _, dept := range depts {
		// 当前节点的pid 如果 等于 pid 那么就说明他有子集
		if dept.PID == pid {
			children := newTree(depts, dept.ID)
			parent := models.DeptTree{
				Model:    dept.Model,
				PID:      dept.PID,
				Name:     dept.Name,
				Children: children,
			}
			trees = append(trees, &parent)
		}
	}
	return trees
}
